package com.joint.core.service.listener;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Sets;
import com.joint.base.entity.Duty;
import com.joint.base.entity.ProcessConfig;
import com.joint.base.entity.TaskFlow;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.exception.workflow.PcfgSysNotExistException;
import com.joint.base.service.*;
import org.activiti.engine.EngineServices;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.impl.persistence.entity.HistoricVariableInstanceEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * Created by hpj on 2015/1/16.
 */
@Component
@Transactional
public class TaskEventListener implements ActivitiEventListener {

    @Resource
    private UsersService usersService;
    @Resource
    private ProcessConfigService processConfigService;
    @Resource
    private DutyService dutyService;
    @Resource
    private BusinessConfigService businessConfigService;
    @Resource
    private SessionFactory sessionFactory;
    @Resource
    private TaskFlowService taskFlowService;

    @Override
    public void onEvent(ActivitiEvent event) {
        ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event;
        Object entity = entityEvent.getEntity();

        if(entity instanceof TaskEntity){
            TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();

            LogUtil.info("taskEntityId:"+taskEntity.getProcessInstanceId());
            LogUtil.info("taskEntityDefinitionKey:"+taskEntity.getTaskDefinitionKey());
            if(StringUtils.equals("usertask1",taskEntity.getTaskDefinitionKey())){
                return;
            }
            EngineServices engineServices = entityEvent.getEngineServices();
            HistoryService historyService = engineServices.getHistoryService();
            RuntimeService runtimeService = engineServices.getRuntimeService();
            ManagementService managementService = engineServices.getManagementService();

            //获取上一步操作人，监听器监听到的是当前审批节点对应的流程实例id,下一个节点的key
            List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery().processInstanceId(taskEntity.getProcessInstanceId()).orderByTaskCreateTime().desc().list();


            ProcessConfig processConfig = processConfigService.findConfigByActivityId(taskEntity.getProcessDefinitionId(),taskEntity.getTaskDefinitionKey());

            if(processConfig==null && StringUtils.isEmpty(processConfig.getId())){
                throw new PcfgNotExistException();
            }
            System.out.print("节点:"+taskEntity.getTaskDefinitionKey()+" 实例Id:"+taskEntity.getProcessInstanceId()+" 任务Id:"+taskEntity.getId());

            Duty hisDuty;
            Set<String> idList = Sets.newHashSet();
            LogUtil.info("processConfig.getType():"+processConfig.getType());
            LogUtil.info("hisTaskList.size():"+hisTaskList.size());
            if(processConfig.getType()!=-1 && hisTaskList.size()>0){
                LogUtil.info("do spec:");

                HistoricTaskInstanceEntity hisTask = (HistoricTaskInstanceEntity) hisTaskList.get(0);
                List<HistoricVariableInstance> histance = historyService.createHistoricVariableInstanceQuery().taskId(hisTask.getId()).variableName("curDutyId").list();
                LogUtil.info("histance.size():"+histance.size());
                if(histance.size()>0){
                    HistoricVariableInstanceEntity hisVarEntity = (HistoricVariableInstanceEntity) histance.get(0);
                    String id = hisVarEntity.getTextValue();
                    LogUtil.info("id :"+id );
                    hisDuty = dutyService.get(id);
                    idList.addAll(processConfigService.findSpecailByUser(processConfig, hisDuty));
                }
            }
            //查找域对应的候选人
            String fieldStr = processConfig.getVariable();
            LogUtil.info("fieldStr:"+fieldStr);
            if(StringUtils.isNotEmpty(fieldStr)){
//                BusinessConfig businessConfig = businessConfigService.getBusinessConfigByDefintionId(taskEntity.getProcessDefinitionId());
                //获取发起流程时对应的实例
//                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processDefinitionId(taskEntity.getProcessDefinitionId()).processInstanceId(taskEntity.getProcessInstanceId()).singleResult();
                //业务对象的ID
//                String businessKey = historicProcessInstance.getBusinessKey();

//                Map<String,Object> rMap = WorkflowUtils.initMappings(sessionFactory);
//                String entityKey= rMap.get(businessConfig.getTableKey()).toString();
//                Session session=sessionFactory.getCurrentSession();
//                Object targetObj = session.get(entityKey, businessKey);
//                String[] fields = fieldStr.split(",");
                //只有域值所选对象有组织结构时才算做候选对象
//                Set<Users> usersSet= fieldDutyService.findDutyByField(targetObj, businessKey, fields);
//                if(usersSet.size()>0){
//                    for(Users users:usersSet){
//                        idList.add(users.getId());
//                    }
//                }

                //通过taskEntity的参数得到Users
                Collection<String> uids = (Collection<String>) taskEntity.getVariable(fieldStr);
                if(uids.size()>0){
                    for(String id: uids){
                        LogUtil.info("id:"+id);
                        idList.add(id);
                    }
                }

            }
            List<Duty> dutyList = processConfigService.findDutyByConfig(processConfig);

            if(dutyList!=null && dutyList.size()>0){
                for(Duty duty :dutyList){
                    idList.add(duty.getUsers().getId());
                }
            }

            LogUtil.info("idList.size:" + idList.size());
            if(idList.size()==0){
                throw new PcfgSysNotExistException();
            }

            taskEntity.addCandidateUsers(idList);

            /**
             * 通过任务流程表记录每个任务的即将操作人
             */
            for(String id:idList){
                TaskFlow taskFlow = new TaskFlow();
                taskFlow.setUsers(usersService.get(id));
                taskFlow.setTaskId(taskEntity.getId());
                taskFlowService.save(taskFlow);
            }

        }
    }

    @Override
    public boolean isFailOnException() {
        return true;
    }
}
